<template>
  <div class="dialog">

    <el-dialog :title="title" :visible.sync="isShowDialogComponent"
               width="50%" :before-close="handleClose">
      <el-form ref="formRef" :model="form"
               label-width="100px" :rules="formRules"
               v-loading="loading" element-loading-text="拼命加载中......"
               element-loading-spinner="el-icon-loading">
        <el-form-item label="学期名称 :" prop="Title">
          <el-input v-model="form.Title" :maxlength="40"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose" :disabled="loading">取 消</el-button>
        <el-button type="primary" @click="submitEvent" :disabled="loading">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
//引入封装的接口的类名
import Semester from '../../../model/semester'
//引入封装的验证规则，包括价格、手机等的一些特殊验证
import ProofRules from '../../../ck/util/proofRules'

export default {
  name: 'AddAndEditDialog',
  props: {
    title: String,
    isShowDialogComponent: Boolean,
    judgeId: Number
  },
  data () {
    return {
      loading: false,
      form: {
        Title: '',
        ID:0
      },
      formRules: {
        Title: ProofRules.requiredFieldAndLength('学期名称', 2, 40),
      },
      //保存获取的学科的集合
      semesterList: [],
    }
  },
  created () {
    //判断点击的是否是编辑按钮
    this.judgeEditButton()
  },
  methods: {
    handleClose (payload) {
      this.$emit('handleClose', payload)
    },
    submitEvent () {
      //提交前先进行表单验证
      this.$refs.formRef.validate(async valid => {
        if (valid) {
          try {
            //判断是否时添加操作
            if (this.judgeId === 0) {
              this.loading = true
              await Semester.Add(this.form)
              this.loading = false
              this.$message.success('添加学期信息成功')
              this.handleClose('submitButton')
            } else {
              //如果是编辑操作
              this.loading = true
              this.form.ID=this.judgeId
              await Semester.Update(this.form)
              this.loading = false
              this.$message.success('编辑学期信息成功')
              this.handleClose('submitButton')
            }
          } catch (err) {
            this.loading = false
          }
        } else {
          this.$message.error('请填写表单必填项')
        }
      })
    },
    //判断点击的是否是编辑按钮
    async judgeEditButton () {
      if (this.judgeId === 0) {
        this.subjectLabel = '选择学科 :'
      } else if (this.judgeId !== 0) {
        this.subjectLabel = '选定学科为 :'
        const res = await Semester.SearchModelDetails({ ID: this.judgeId })
        this.form = res
      }
    },
  }
}
</script>

<style scoped>
/deep/.el-input__inner{
  width: 80%;
}
</style>
